/**
 * Created by XiMing on 2015/6/21.
 */
var fs          = require('fs');
var path        = require('path');
var Sequelize   = require('sequelize');
var env         = process.env.NODE_ENV || "development";
var config      = require('../config.json')[env];
var dboptions   = config["db"];
var client = new Sequelize(dboptions.database,
    dboptions.username,
    dboptions.password, {
        host: dboptions.host,
        dialect: dboptions.dialect,
        pool: dboptions.pool
    });
var models = {};

fs
    .readdirSync(__dirname + '/models')
    .filter(function (file) {
        return (file.indexOf('.') !== 0) && (file !== 'index.js');
    })
    .forEach(function (file) {
        var model = client.import(path.join(__dirname + '/models', file));
        models[model.name] = model;
    });

Object.keys(models).forEach(function (modelName) {
    if (models[modelName].options.hasOwnProperty('associate')) {
        models[modelName].options.associate(models);
    }
});

module.exports = models;
module.exports.client = client;